<?php
// +----------------------------------------------------------------------

namespace app\user\model;

use app\user\model\Member as MemberModel;
use think\Model as ThinkModel;
use app\user\model\Vip as VipModel;
use app\user\model\Level as LevelModel;
use think\facade\Db;
use util\Wxsdk;

/**
 * 返佣模型
 * @package app\cms\model
 */
class Rebate extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'user_rebate';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 获取返佣列表
     * @return array|mixed
     */
    public static function getList($map = [], $order = [], $paginate = 0)
    {
		if ($paginate == 0) $paginate = config('paginate');
        $data_list = self::view('user_rebate', true)
            ->view("user_vip", ['realname','mobile','group', 'pid'], 'user_vip.member_id=user_rebate.uid', 'left')
            ->where($map)
            ->order($order)
            ->paginate($paginate);
        return $data_list;
    }
    /**
     * 保存返佣记录
     * @return array|mixed
     */
    public function saveData($uid = 0, $type = 1, $model = 1, $pay = 0, $oid = 0)
    {
		if ($uid == 0 || $pay == 0) return false;
		
		$vip = new VipModel;
		$user = $vip->where('member_id', '=', $uid)->find();
		if (!$user || $user['pid'] <= 0) return false;
		$fathers = $vip->getFathers($user['pid']);
		if (!$fathers) return false;
		$rebate = 0;
		$rebate_list = [];
		foreach ($fathers as $father) {
			$config = LevelModel::Config($father['group']);
			if ($model == 1) { //首购
				$pre = $config['first'];
			} else { //复购
				$pre = $config['second'];
			}
			if ($pre - $rebate > 0) { //有剩余返佣
				$this_pre = $pre - $rebate;
				$rebate = $pre;
				$money = $pay * $this_pre / 100;
				$father_info = $vip->where('member_id', '=', $father['member_id'])->find();
				$rebate_list[] = [
					'uid'		=> $father['member_id'],
					'type'		=> $type,
					'model'		=> $model,
					'money'		=> $money,
					'pre'		=> $this_pre,
					'pay'		=> $pay,
					'from_uid'	=> $uid,
					'oid'		=> $oid,
					'money_take'=> $father_info['money_take'] + $money,
				];
				// 保存用户可返佣金额
				$father_info->money_take = ['inc', $money];
				$father_info->save();
                $payer = MemberModel::getOpenid($uid);//openid
                $sendData = [
                    'template_id'   => 'p_w1OOGDWSex5lOVBRMqYnPK_jwatDMvRudPz0Bx_i8',//模板消息ID
                    'touser'    => $payer,//用户openid
                    'data'=>[
                        'first'=>[
                            'value'=>'您获得了一笔新的佣金！',
                            'color'=>'#000000',
                        ],
                        'keyword1'=>[
                            'value'=>$father_info->money_take,//佣金金额
                            'color'=>'#000000'
                        ],
                        'keyword2'=>[//时间
                            'value'=>date('Y-m-d H:i:s',time()),
                            'color'=>'#000000'
                        ],
                        'remark'=>[
                            'value'=>'订单完成，感谢您的付出，欢迎下次光临！',//描述
                            'color'=>'#173177',
                        ],
                    ]
                ];
                $this->template($sendData);
			}
			
		}
		
		// 保存返佣列表
		if ($rebate_list){
			$rebateModel = new self;
			return $rebateModel->saveAll($rebate_list);
		}
    }

    // 发送微信模板消息
    protected function template($data)
    {
        $wxsdk = new Wxsdk;
        return $wxsdk->template($data);
    }
	/**
	 * 返佣类型
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array|static
	 */
	public static function type($id = 99)
	{
		$types = [
			1 => '后台充值',
			2 => '商品下单',
			3 => '返佣提现',
		];
	    if ($id === 99) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
	/**
	 * 返佣模式
	 * @param int $id 模式id
	 * @author paulxun
	 * @return array|static
	 */
	public static function model($id = 99)
	{
		$types = [
			1 => '首购返佣',
			2 => '复购返佣',
			3 => '申请提现',
		];
	    if ($id === 99) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
}
